﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sio.Mdm.Server;
using Sio.Mdm.Types;
using Sio.Mdm.Entities;
using IDM.BF.AdministrationService;
using System.Data.Common;
using FirebirdSql.Data.FirebirdClient;
using System.IO;
using IDM.Types;

namespace IDM.BL.AdministrationService
{
    [Service(Name = "AuthorizationService", DefaultInterface = typeof(BF.AdministrationService.IAuthorizationService))]
    public class AuthorizationService : Sio.Mdm.BL.Base.BaseFirebird<User>, BF.AdministrationService.IAuthorizationService
    {
        public AuthorizationService()
            : base("IDM")
        {
        }

        #region IAuthorizationService Members

        public Sio.Mdm.Types.Result Login(string userName, string password, out Session session)
        {
            session = null;

            Criteria criteria = new Criteria();
            criteria.Query.SetExpression(new QueryParameter("Username", userName)
                .And(new QueryParameter("\"Password\"", password)
            ));

            User user = null;
            IUsersService users = Server.GetService(typeof(IUsersService)) as IUsersService;
            Result error = users.Select(ref user, criteria, session);

            if (error == null && user != null)
            {
                session = new Sio.Mdm.Types.Session(user.ID, Guid.NewGuid(), userName);
            }
            else
            {
                return new Types.Administration.AuthorizationFailedError(userName);
            }
            
            return error;
        }

        public Result Logout(ref Session session)
        {
            session = Session.Empty;
            // TODO : Maybe do some log or something
            return null;
        }
        public Result CreateDatabase()
        {
            string[] sqlLines = Properties.Resources.metadata.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            DbTransaction transaction = BeginTransaction();

            foreach (string line in sqlLines)
            {
                ExecuteNonQuery(line, transaction);
            }

            CommitTransaction(transaction);

            return null;
        }
        public Result HasDatabase()
        {
            FbConnectionStringBuilder builder = new FbConnectionStringBuilder(GetConnectionString());
            builder.Database = Environment.ExpandEnvironmentVariables(builder.Database);
            return File.Exists(builder.Database)? null : new Result("Database missing!");
        }
        #endregion
    }
}
